package 链表;

import java.util.Arrays;

/**
 * https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/
 * <p>
 * 示例 1:
 * <p>
 * 输入: head = [4,5,1,9], val = 5
 * 输出: [4,1,9]
 * 解释: 给定你链表中值为5的第二个节点，那么在调用了你的函数之后，该链表应变为 4 -> 1 -> 9.
 * 示例 2:
 * <p>
 * 输入: head = [4,5,1,9], val = 1
 * 输出: [4,5,9]
 * 解释: 给定你链表中值为1的第三个节点，那么在调用了你的函数之后，该链表应变为 4 -> 5 -> 9.
 */
public class 剑指_Offer_18_删除链表的节点 {

    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5, new ListNode(6, null))))));
        ListNode listNode2 = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5, new ListNode(6, null))))));
        System.out.println((deleteNode(listNode1, 3)));
        System.out.println((deleteNode1(listNode2, 3)));
    }

    public static ListNode deleteNode(ListNode head, int val) {

        if (head == null) return null;

        ListNode node = deleteNode(head.next, val);
        head.next = node;
        if (head.val == val) {
            return head.next;
        }

        return head;
    }

    //双指针
    public static ListNode deleteNode1(ListNode head, int val) {
        if (head.val == val) return head.next;

        ListNode pre = head, cur = head.next;

        while (cur != null && cur.val != val) {
            pre = pre.next;
            cur = cur.next;
        }

        if (cur != null) pre.next = cur.next;

        return head;
    }
}
